<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\brand\Brand;
use Biz\model\brand\Brand as mBrand;
use Biz\model\brand\BrandPackage;
use Biz\model\brandAccount\BrandAccountAuth;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\brandAccount\BrandAccountLog;
use Biz\model\brandAccount\BrandAccountShop;
use Biz\model\wiki\Wiki as mWiki;
use Biz\service\brand\BrandService;
use Biz\service\brandAccount\BrandAccount;
use Doraemon\cache\User as cUser;
use Doraemon\cache\UserAuthStatus as cUserAuthStatus;
use Doraemon\cache\UserNick;
use Doraemon\model\Member as mMember;
use Doraemon\service\DingTalkAlert;
use Doraemon\service\Follow;
use Doraemon\service\Member;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

/**
 * 新品牌账户管理
 */
class BrandAccountInfoController extends Controller
{
    const PAGE_SIZE = 20;
    const DEFAULT_BRAND_UID = ['6587838']; //默认ID

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $params = $request->all();
        $type = $request->input('type', BrandAccountInfo::ACCOUNT_TYPE_BRAND);
        //搜索过滤
        $params['type'] = $type;
        $where = $this->buildWhere($params);
        $result = BrandAccount::admGetAccountList($where);

        $list = !empty($result['list']) ? $result['list'] : [];
        $total = $result['total'];
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $params['per_page'],
        ]);

        $allPackageTypes = BrandPackage::allPackageTypes();

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($allPackageTypes, $type) {
            $grid->filter(function (Grid\Filter $filter) use ($allPackageTypes, $type) {
                $filter->disableIdFilter();
                if ($type == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->dropDown('uid_value', [
                            'uid' => 'uid',
                            'nick' => '用户昵称',
                        ]);
                        $filter->dropDown('brand_value', [
                            'brand_id' => '品牌id',
                            'brand_name' => '品牌名称',
                        ]);
                        $filter->equal('start_time', '开始时间')->date();
                        $filter->equal('end_time', '结束时间')->date();
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) use ($allPackageTypes) {
                        $filter->equal('pack_type', '品牌套餐')->select($allPackageTypes);
                        $filter->equal('brand_type', '品牌身份')->select(mBrand::BRAND_TYPE);
                        $filter->equal('auth_status', '认证状态')->multipleSelect(BrandAccountInfo::AUTH_STATUS_MAP);
                        $filter->equal('account_status', '账户状态')->multipleSelect(BrandAccountInfo::ACCOUNT_STATUS_MAP);
                    });
                } else {
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('uid', 'uid');
                        $filter->equal('nick', '用户昵称');
                        $filter->equal('start_time', '开始时间')->date();
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) use ($allPackageTypes) {
                        $filter->equal('auth_status', '认证状态')->select(BrandAccountInfo::AUTH_STATUS_MAP);
                        $filter->equal('account_status', '账户状态')->select(BrandAccountInfo::ACCOUNT_STATUS_MAP);
                        $filter->equal('end_time', '结束时间')->date();
                    });
                }
                $filter->expand();
            });

            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->column('id', '账户id')->width(80);
            $grid->column('uid', 'uid')->width(80);
            $grid->column('nick', '昵称')->width(100);
            $grid->column('avatar_small', '图像')->display(function () {
                return '<img src="' . $this->small_avatar . '">';
            })->width(80);
            if ($type == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                $grid->column('brand_id', '品牌id')->width(80);
                $grid->column('brand_name', '品牌名称')->width(120);
                $grid->column('logo', '品牌logo')->display(function () {
                    return '<img src="' . $this->logo . '" style="width:52px;height:52px">';
                })->width(80);
                $grid->column('pack_type', '品牌套餐')->display(function () use ($allPackageTypes) {
                    return $allPackageTypes[$this->pack_type];
                })->width(120);
                $grid->column('brand_type', '品牌身份')->display(function () {
                    return mBrand::BRAND_TYPE[$this->brand_type];
                })->width(120);
            }
            $grid->column('account_status', '账户状态')->display(function () {
                return BrandAccountInfo::ACCOUNT_STATUS_MAP[$this->account_status];
            })->width(120);
            $grid->column('auth_status', '认证状态')->display(function () {
                return BrandAccountInfo::AUTH_STATUS_MAP[$this->auth_status];
            })->width(120);
            $grid->column('add_time', '申请时间')->width(120);
            $grid->column('in_end_time', '入驻结束')->width(120);
            $grid->column('tags', '标记类型')->width(80);
            $grid->column('level', '等级')->width(80);
            $grid->column('growth_value', '成长值')->width(80);
            $grid->column('brand_score', '品牌指数')->width(80);
            $grid->column('reason', '说明')->width(80)->limit(30);
            $grid->column('admin_id', '处理人')->display(function () {
                if (!$this->admin_id) {
                    return '-';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            })->width(80);

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->append("<a href=\"/admin/brand/account/index/" . $actions->row->id . "/1\"
                    class=\"btn btn-primary\" style=\"margin-top: 5px;margin-left: 5px;\">编辑</a>");
                if ($actions->row->account_status == BrandAccountInfo::ACCOUNT_STATUS_USED) {
                    $upgradeArr = BrandService::getUpgradePackArr($actions->row->pack_type);
                    if ($actions->row->type == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                        if ($actions->row->uid && $actions->row->brand_id) {
                            $strCode = empty($upgradeArr) ? '生成付款码(续费)' : '生成付款码(续费/升级)';
                            $strOrder = empty($upgradeArr) ? '添加付费订单(续费)' : '添加付费订单(续费/升级)';
                            if (Admin::user()->can('brand.pay')) {
                                $actions->append("<a href=\"/admin/brand/pay/qrcode/" . $actions->row->id .
                                    "\" class=\"btn btn-success\" style=\"margin-top: 5px;margin-left: 5px;\">" . $strCode . "</a>");
                            }
                            $actions->append("<a href=\"/admin/brand/upgrade/order/" . $actions->row->id .
                                "/add\" class=\"btn btn-success\" style=\"margin-top: 5px;margin-left: 5px;\">" . $strOrder . "</a>");
                        }
                        if ($actions->row->brand_type == mBrand::BRAND_TYPE_DEFAULT) {
                            $actions->append("<a href=\"/admin/brand/account/index/" . $actions->row->id . "/setBrandType/3\" 
                            class=\"btn btn-success\" style=\"margin-top: 5px;margin-left: 5px;\" onclick=\"return confirm('确认设置为精选品牌？');\">设置为精选品牌</a>");
                        } elseif ($actions->row->brand_type == mBrand::BRAND_TYPE_COMMON) {
                            $actions->append("<a href=\"/admin/brand/account/index/" . $actions->row->id . "/setBrandType/3\" 
                            class=\"btn btn-success\" style=\"margin-top: 5px;margin-left: 5px;\" onclick=\"return confirm('确认设置为精选品牌？');\">设置为精选品牌</a>");
                            $actions->append("<a href=\"/admin/brand/account/index/" . $actions->row->id . "/setBrandType/4\" 
                            class=\"btn btn-success\" style=\"margin-top: 5px;margin-left: 5px;\" onclick=\"return confirm('确认设置为超级品牌？');\">设置为超级品牌</a>");
                        } elseif ($actions->row->brand_type == mBrand::BRAND_TYPE_BEST) {
                            $actions->append("<a href=\"/admin/brand/account/index/" . $actions->row->id . "/setBrandType/4\" 
                            class=\"btn btn-success\" style=\"margin-top: 5px;margin-left: 5px;\" onclick=\"return confirm('确认设置为超级品牌？');\">设置为超级品牌</a>");
                        }
                    }
                } else if (in_array($actions->row->account_status, [BrandAccountInfo::ACCOUNT_STATUS_DEFAULT, BrandAccountInfo::ACCOUNT_STATUS_EXPIRE])) {
                    if ($actions->row->type == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                        if (in_array($actions->row->auth_status, [BrandAccountInfo::AUTH_STATUS_PASS, BrandAccountInfo::AUTH_STATUS_EXPIRE])) {
                            if (!$actions->row->pack_type || !empty($upgradeArr)) {
                                if ($actions->row->uid && $actions->row->brand_id) {
                                    $strCode = '生成付款码';
                                    $strOrder = '添加付费订单';
                                    if (Admin::user()->can('brand.pay')) {
                                        $actions->append("<a href=\"/admin/brand/pay/qrcode/" . $actions->row->id .
                                            "\" class=\"btn btn-success\" style=\"margin-top: 5px;margin-left: 5px;\">" . $strCode . "</a>");
                                    }
                                    $actions->append("<a href=\"/admin/brand/upgrade/order/" . $actions->row->id .
                                        "/add\" class=\"btn btn-success\" style=\"margin-top: 5px;margin-left: 5px;\">" . $strOrder . "</a>");
                                }
                            }
                        }
                    } else {
                        $actions->append("<a href=\"/admin/brand/account/index/" . $actions->row->id . "/openShop\" 
                            class=\"btn btn-success\" style=\"margin-top: 5px;margin-left: 5px;\"onclick=\"return confirm('确认开通店铺？');\">开通</a>");
                    }
                    $actions->disableDelete(false);
                }
            });
        });
        if ($type == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
            $header = '品牌账户管理';
            $url = '/brand/account/index';
        } else {
            $header = '店铺账户管理';
            $url = '/brand/account/index?type=' . BrandAccountInfo::ACCOUNT_TYPE_SHOP;
        }
        return $content
            ->header($header)
            ->breadcrumb(
                ['text' => $header, 'url' => $url]
            )
            ->body($listGrid);
    }

    private function buildWhere($params = [])
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : 10;
        $limit = [($page - 1) * $pageSize, $pageSize];

        $where = [
            'type' => $params['type'],
            'LIMIT' => $limit,
            'ORDER' => ['id' => 'DESC']
        ];
        if (isset($params['uid']) && $params['uid']) {
            $where['uid'] = $params['uid'];
        }
        if (isset($params['nick']) && strlen($params['nick']) > 0) {
            $where['nick'] = trim($params['nick']);
        }
        if (isset($params['brand_id']) && $params['brand_id']) {
            $where['brand_id'] = $params['brand_id'];
        }
        if (isset($params['brand_name']) && $params['brand_name']) {
            $brandIds = mBrand::selectByWhere(['brand_name[~]' => $params['brand_name'], 'status' => mBrand::STATUS_NORMAL], ['id']);
            $brandIds = $brandIds ? array_column($brandIds, 'id') : [];
            if ($brandIds) {
                $where['brand_id'] = $brandIds;
            }
        }
        if (isset($params['pack_type']) && $params['pack_type']) {
            $brandIds = mBrand::selectByWhere(['pack_type' => $params['pack_type'], 'status' => mBrand::STATUS_NORMAL], ['id']);
            $brandIds = $brandIds ? array_column($brandIds, 'id') : [];
            if ($brandIds) {
                $where['brand_id'] = $brandIds;
            }
        }
        if (isset($params['brand_type']) && isset(mBrand::BRAND_TYPE[$params['brand_type']])) {
            $where['brand_type'] = $params['brand_type'];
        }
        if (isset($params['auth_status'])) {
            $where['auth_status'] = $params['auth_status'];
        }
        if (isset($params['account_status'])) {
            $where['account_status'] = $params['account_status'];
        }
        if (isset($params['start_time']) && $params['start_time']) {
            $where['in_start_time[>=]'] = $params['start_time'];
        }
        if (isset($params['end_time']) && $params['end_time']) {
            $where['in_end_time[<=]'] = $params['end_time'];
        }
        return $where;
    }

    public function edit(Request $request, Content $content, $id, $step)
    {
        $requestParams = $request->all();
        $auth_id = $request->input('auth_id', 0);
        if (!$id) {
            $data = [];
        } else {
            $data = BrandAccount::admGetAccountInfo($id, $auth_id);
            $button = '';
        }
        $tab = new Tab();
        $accountUrl = '/admin/brand/account/index/' . $id . '/1';
        $authUrl = '/admin/brand/account/index/' . $id . '/2';
        $shopUrl = '/admin/brand/account/index/' . $id . '/3';
        if ($data['account']['type'] == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
            $header = '品牌账户信息';
            $parentUrl = url('/admin/brand/account/index');
        } else {
            $header = '店铺账户信息';
            $parentUrl = url('/admin/brand/account/index') . '?type=2';
        }
        if ($auth_id) {
            if ($data['account']['type'] == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                $header = '品牌认证信息';
            } else {
                $header = '店铺认证信息';
            }
            $parentUrl = url('/admin/brand/account/auth/index');
            $accountUrl .= '?auth_id=' . $auth_id;
            $authUrl .= '?auth_id=' . $auth_id;
            $shopUrl .= '?auth_id=' . $auth_id;
        }
        $tab->addLink('账户信息', $accountUrl, $step == 1);
        $tab->addLink('认证信息', $authUrl, $step == 2);
        $tab->addLink('店铺信息', $shopUrl, $step == 3);
        return $content
            ->header($header)
            ->breadcrumb(
                ['text' => $header . '管理', 'url' => $parentUrl],
                ['text' => $header]
            )
            ->body($button . $tab)->row(self::_form($data, $id, $step, $requestParams, $auth_id));
    }

    private function _form($data, $id, $step, $request, $auth_id = 0)
    {
        $requestUlr = $this->getCurrentUrl();
        $accountInfo = $data['account'];
        $authInfo = $data['auth'];
        $shopList = $data['shop'];
        $type = $accountInfo['type'];
        if ($step == 1) {
            $brandList = mBrand::select(['id', 'brand_name', 'status']);
            $brandsOption = [];
            $have_brand = BrandAccountInfo::getAllByWhere(['account_status[!]' => BrandAccountInfo::ACCOUNT_STATUS_DEL, 'brand_id[>]' => 0], ['uid', 'brand_id']);
            $have_brand = array_column($have_brand, 'uid', 'brand_id');
            foreach ($brandList as $row) {
                $val = $row['brand_name'] . '[' . $row['id'] . ']';
                if (isset($have_brand[$row['id']])) {
                    $val .= '[已绑定uid:' . $have_brand[$row['id']] . ']';
                }
                if ($row['status'] == mBrand::STATUS_DELETE) {
                    $val .= '[已删除]';
                }
                $brandsOption[$row['id']] = $val;
            }
            $member = mMember::getUidByNick($data['nick']);
            $form = new Form($accountInfo);
            $form->hidden('request_url', 'request_url')->default($requestUlr);
            $form->text('id', '账户id')->readOnly()->setWidth(4, 2);
            $form->text('uid', 'uid')->readOnly()->setWidth(4, 2);
            $form->select('account_status', '账户状态')->options(BrandAccountInfo::ACCOUNT_STATUS_MAP)->readOnly()->setWidth(4);
            if ($type == 1) {
                if ($accountInfo['account_status'] == BrandAccountInfo::ACCOUNT_STATUS_USED && $accountInfo['brand_id'] > 0) {
                    $form->select('brand_id', '品牌')
                        ->options($brandsOption)->readOnly()->setWidth(4)->required();
                } else {
                    $form->select('brand_id', '品牌')
                        ->options($brandsOption)->setWidth(4)->required();
                }

                $form->text('level', '商家等级')->readOnly()->setWidth(4);
                $form->text('growth_value', '成长值')->readOnly()->setWidth(4);
                $form->text('brand_score', '品牌指数')->readOnly()->setWidth(4);

                $form->select('brand_type', '品牌身份')->options(mBrand::BRAND_TYPE)->readOnly()->setWidth(4);
            }
            $form->text('nick', $member && $member != $accountInfo['uid'] ? '账户认证昵称 [昵称已被使用,请修改!!!]' : '账户认证昵称')->setWidth(4, 2)->required()
                ->help('昵称只能是中文、英文、数字、中划线-、下划线_ ; 中文2~12字 ; 英文/数字4~24字符 ; 不能为纯数字')->required();
            $form->textarea('descrip', '账户介绍')->setWidth(4, 2)->attribute('maxlength', 20);
            $form->text('add_time', '申请时间')->readOnly()->setWidth(4, 2);
            $form->select('type', '认证身份')->readOnly()->options(BrandAccountInfo::ACCOUNT_TYPE)->setWidth(4);
            $form->select('auth_status', '认证状态')->options(BrandAccountInfo::AUTH_STATUS_MAP)->readOnly()->setWidth(4);
            $form->textarea('reason', '不通过原因')->readOnly()->setWidth(4, 2);
            if ($type == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                $form->date('in_start_time', '入驻起始时间')->setWidth(4, 2)->readOnly();
                $form->date('in_end_time', '入驻结束时间')->setWidth(4, 2)->readOnly();
            } else {
                $form->date('in_start_time', '入驻起始时间')->setWidth(4, 2)->required();
                $form->date('in_end_time', '入驻结束时间')->setWidth(4, 2)->required();
            }
            $form->textarea('remark', '补充说明')->setWidth(4, 2);
            $form->text('tags', '标记')->setWidth(4, 2);
            $form->action('/admin/brand/account/index/' . $id . '/1/save');
            return $form->render();
        } elseif ($step == 2) {
            if (!empty($authInfo)) {
                if ($authInfo['auth_status'] == BrandAccountAuth::AUTH_STATUS_DEFAULT) {
                    $button = '<div style="text-align: right"><a href="/admin/brand/account/auth/' . $authInfo['id'] . '/audit/' . BrandAccountAuth::AUTH_STATUS_PASS . '" class="btn btn-primary" onclick="return confirm(\'确认通过审核!!!!\');">审核通过</a>
                    <a href="javascript:layer.open({
                        type: 2,
                        title: \'审核不通过\',
                        maxmin: true,
                        area: [\'500px\', \'400px\'],
                        content: \'/admin/brand/account/auth/noPass/' . $authInfo['id'] . '\'
                        });" class="btn btn-primary">审核不通过</a></div>';
                } elseif ($authInfo['auth_status'] == BrandAccountAuth::AUTH_STATUS_NOPASS) {
                    $button = '<div style="text-align: right"><a href="/admin/brand/account/auth/' . $authInfo['id'] . '/audit/' . BrandAccountAuth::AUTH_STATUS_PASS . '" class="btn btn-primary" onclick="return confirm(\'确认通过审核!!!!\');">审核通过</a></div>';
                }
                $form = new Form($authInfo);
                $form->hidden('request_url', 'request_url')->default($requestUlr);
                $form->hidden('id');
                $form->text('nick', '昵称')->setWidth(4, 2)->readonly();
                $form->select('auth_status', '认证状态')->options(BrandAccountAuth::AUTH_STATUS_MAP)->readOnly()->setWidth(4);
                $form->text('company', '企业名称')->setWidth(4, 2)->required();
                $form->text('credit_code', '社会统一信用代码')->setWidth(4, 2);
                $form->imgUpload('license', '营业执照', false, ['isUpload' => true, 'isGetUrl' => true, 'imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE]);
                $form->date('license_time', '营业执照有效期')->setWidth(4, 2);
                $form->text('name', '姓名')->setWidth(4, 2)->required();
                $form->text('phone', '电话')->setWidth(4, 2);
                $form->text('email', '邮箱')->setWidth(4, 2);
                $form->text('weixin', '微信')->setWidth(4, 2);
                $form->imgUpload('letter', '认证申请函', false, ['isUpload' => true, 'isGetUrl' => true, 'imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE]);
                $form->date('letter_time', '认证申请函有效期')->setWidth(4, 2)->required();
                $form->date('auth_start_time', '认证申请开始时间')->setWidth(4, 2)->required();
                $form->date('auth_end_time', '认证申请结束时间')->setWidth(4, 2)->required();
                if ($accountInfo['type'] == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                    $form->imgUpload('certificate', '商标注册证', true, ['isUpload' => true, 'isGetUrl' => true, 'imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE])->help('支持多张图');
                    $form->imgUpload('application', '产品专利或专利申请证明', false, ['isUpload' => true, 'isGetUrl' => true, 'imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE]);
                }
                $form->imgUpload('authorization', '授权书', true, ['isUpload' => true, 'isGetUrl' => true, 'imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE])->help('支持多张图');
                $form->action('/admin/brand/account/index/' . $id . '/2/save');
                return $button . $form->render();
            } else {
                return "当前没有审核通过的认证信息,你可以去<a href='" . url('/admin/brand/account/auth/index') . "'>「品牌认证管理」</a>页面审核";
            }
        } elseif ($step == 3) {
            if ($shopList) {
                $shopIds = array_column($shopList, 'shop_id');
                $havShop = BrandAccountShop::select(['id', 'account_id', 'name', 'shop_id'], ['shop_id' => $shopIds, 'shop_status' => BrandAccountShop::SHOP_STATUS_VALID]);
                if ($havShop) {
                    foreach ($shopList as $_k => &$_v) {
                        foreach ($havShop as $_sk => &$_sv) {
                            if ($_v['shop_id'] == $_sv['shop_id'] && $_v['id'] != $_sv['id']) {
                                $_v['have_shop'][$_sv['account_id']] = '<a target="_blank" href="/admin/brand/account/index/' . $_sv['account_id'] . '/3" >' . $_sv['id'] . ',点击查看</a>';
                            }
                        }
                        if (isset($_v['have_shop'])) {
                            $_v['have_shop'] = implode('<br/>', $_v['have_shop']);
                        } else {
                            $_v['have_shop'] = '';
                        }
                    }
                }
            }
            $gridModel = new pGridDataModel($shopList);
            $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($id, $step, $auth_id) {
                $grid->disableFilter();
                $grid->disableTools();
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disablePagination();
                $grid->column('id', 'id')->width(100);
                $grid->column('type', '类别')->display(function () {
                    if (isset(BrandAccountShop::SHOP_TYPE[$this->type])) {
                        return BrandAccountShop::SHOP_TYPE[$this->type];
                    }
                })->width(100);
                $grid->column('other_type', '其他平台')->width(100);
                $grid->column('name', '店铺名称')->width(100);
                $grid->column('url', '店铺地址')->width(150);
                $grid->column('shop_id', '店铺id')->width(100);
                $grid->column('have_shop', '已绑定店铺')->display(function () {
                    return $this->have_shop;
                })->width(100);
                $grid->column('letter_img', '认证公函')->display(function ($letter_img) {
                    return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'600px\', \'500px\'],content: \'' . $letter_img . '\'});">
                                <img width="100px" height="50px" src="' . $letter_img . '">
                            </a>';
                });
                $grid->column('authorization_img', '授权文件')->display(function ($authorization_img) {
                    return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'600px\', \'500px\'],content: \'' . $authorization_img . '\'});">
                                <img width="100px" height="50px" src="' . $authorization_img . '">
                            </a>';
                })->width(100);
                $grid->column('add_time', '添加时间')->width(150);
                $grid->column('admin_id', '处理人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                })->width(80);
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($id, $step, $auth_id) {
                    $actions->disableView();
                    $actions->disableDelete();
                    $actions->disableEdit();
                    if (!$auth_id) {
                        $actions->append("<a href=\"/admin/brand/account/index/" . $id . "/3?shop=" . $actions->row->id . "\" class=\"btn btn-primary\">编辑</a>");
                        $actions->append("<a href=\"/admin/brand/account/index/shop/" . $actions->row->id . "/del\" 
                        class=\"btn btn-primary\" onclick=\"return confirm('确认删除？');\">删除</a>");
                    }
                });
            });

            $list = $listGrid->render();
            $shopList = array_column($shopList, null, 'id');
            $accountShopId = $request['shop'] ?? 0;
            $shopInfo = ($accountShopId && isset($shopList[$accountShopId])) ? $shopList[$accountShopId] : [];
            $form = new Form($shopInfo);
            $form->hidden('request_url', 'request_url')->default($requestUlr);
            $form->hidden('auth_id', 'auth_id')->default($auth_id);
            if ($accountShopId) {
                $form->hidden('id');
            }
            $form->select('type', '平台')
                ->options(BrandAccountShop::SHOP_TYPE)
                ->default(1)
                ->setWidth(4, 2);
            if (isset($shopInfo['type']) && $shopInfo['type'] == 4) {
                $form->text('other_type', '其他平台')->setWidth(4, 2);
            }
            $form->text('name', '店铺名称')->setWidth(4, 2)->required();
            $form->text('url', '店铺地址')->setWidth(4, 2)->required();
            $form->text('shop_id', '店铺id')->setWidth(4, 2)->required('不能为空');
            $form->imgUpload('letter', '认证公函', false, [
                'isUpload' => true,
                'isGetUrl' => true,
                'imgType' => ImgUrl::APPTYPE_BIZ,
                'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
            ]);
            $form->imgUpload('authorization', '授权文件', false, [
                'isUpload' => true,
                'isGetUrl' => true,
                'imgType' => ImgUrl::APPTYPE_BIZ,
                'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
            ]);
            $form->action('/admin/brand/account/index/' . $id . '/3/save');
            return $form->render() . $list;
        }
    }

    public function save(Request $request, $id, $step)
    {
        $params = $request->all();
        $requestUrl = $params['request_url'] ?? url()->previous();
        try {
            if (empty($id)) {
                throw new \Exception('不存在的账户id');
            }
            $brandAccount = BrandAccountInfo::getOneByWhere(['id' => $id]);
            if (empty($brandAccount)) {
                throw  new \Exception('不存在的账户信息');
            }
            $adminId = Admin::user()->id;
            switch ($step) {
                case 1://保存账户信息
                    if ($brandAccount['account_status'] == BrandAccountInfo::ACCOUNT_STATUS_USED) {
                        $data = [
                            'nick' => $params['nick'],
                            'descrip' => $params['descrip'],
                            'remark' => $params['remark'],
                            'tags' => $params['tags'],
                        ];
                    } else {
                        $data = [
                            'nick' => $params['nick'],
                            'descrip' => $params['descrip'],
                            'brand_id' => $params['brand_id'],
                            'remark' => $params['remark'],
                            'tags' => $params['tags'],
                        ];
                    }
                    if ($brandAccount['type'] == BrandAccountInfo::ACCOUNT_TYPE_SHOP) {
                        $data = [
                            'nick' => $params['nick'],
                            'descrip' => $params['descrip'],
                            'remark' => $params['remark'],
                            'tags' => $params['tags'],
                        ];
                        if (!empty($params['in_start_time']) || !empty($params['in_end_time'])) {
                            if (strtotime($params['in_start_time']) >= strtotime($params['in_end_time'])) {
                                throw new \Exception('入驻结束时间必须大于开始时间');
                            }
                            $data['in_start_time'] = $params['in_start_time'];
                            $data['in_end_time'] = $params['in_end_time'];
                        }
                    }
                    if ($brandAccount['type'] == BrandAccountInfo::ACCOUNT_TYPE_BRAND && isset($data['brand_id'])) {
                        if ($data['brand_id'] < 1) {
                            throw new \Exception('请选择一个品牌');
                        } else {
                            $otherBrandAccount = BrandAccountInfo::getOneByWhere(['brand_id' => $data['brand_id'], 'id[!]' => $id, 'account_status[!]' => BrandAccountInfo::ACCOUNT_STATUS_DEL]);
                            $otherBrandInfo = mBrand::getBrandInfoById(['id' => $data['brand_id']]);
                            if ($otherBrandAccount && $otherBrandInfo) {
                                throw new \Exception('品牌已使用');
                            }
                        }
                    }
                    if (isset($data['nick']) && $data['nick'] <> '') {
                        $userInfo = mMember::getUser($brandAccount['uid']);
                        if (!in_array($brandAccount['account_status'], [BrandAccountInfo::ACCOUNT_STATUS_USED, BrandAccountInfo::ACCOUNT_STATUS_EXPIRE])) {
                            if ($userInfo && isset($userInfo['nick']) && ($userInfo['nick'] != $data['nick'])) {
                                $result = Member::nick(false, true, $data['nick'], $brandAccount['uid'], isset($userInfo['type']) ? $userInfo['type'] : '');
                                if ($result !== true && $result !== '30天之内只能修改一次用户名' && $result !== '该昵称已被占用') {
                                    throw new \Exception($result);
                                }
                            }
                        }
                    }
                    $oldData = [];
                    foreach ($data as $key => $row) {
                        $oldData[$key] = $brandAccount[$key];
                    }
                    $data['admin_id'] = $adminId;
                    BrandAccountInfo::updateData($data, ['id' => $id]);
                    BrandAccountLog::insertData([
                        'account_id' => $id,
                        'operate_uid' => $adminId,
                        'old_data' => json_encode($oldData, JSON_UNESCAPED_UNICODE),
                        'new_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
                        'operation' => BrandAccountLog::OPERATE_EDIT_ACCOUNT,
                    ]);
                    if ($brandAccount['type'] == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                        if ($data['brand_id'] && $brandAccount['brand_id'] != $data['brand_id']) {
                            mBrand::update(
                                ['uid' => 0],
                                ['id' => $brandAccount['brand_id']]
                            );
                            mBrand::update(
                                ['uid' => $brandAccount['uid']],
                                ['id' => $data['brand_id']]
                            );
                            if ($brandAccount['brand_id']) {
                                mWiki::updateData(['brand_uid' => 0], ['brand_id' => $brandAccount['brand_id']]);
                            }
                            if ($data['brand_id']) {
                                mWiki::updateData(['brand_uid' => $brandAccount['uid']], ['brand_id' => $data['brand_id']]);
                            }
                            $log_data = [
                                'uid' => $brandAccount['uid'],
                                'old_brand_id' => $brandAccount['brand_id'],
                                'new_brand_id' => $data['brand_id'],
                            ];
                            Log::info('品牌账户入驻后台:品牌修改更新uid', $log_data);
                        }
                    }
                    if (isset($data['nick']) && $data['nick'] <> '' && $brandAccount['account_status'] == BrandAccountInfo::ACCOUNT_STATUS_USED) {
                        $res = mMember::updateUserInfo($brandAccount['uid'], ['nick' => $data['nick']]);
                        if (!$res) {
                            throw new \Exception('更改昵称失败');
                        }
                        cUser::deleteUserInfo($brandAccount['uid']);
                        UserNick::update($brandAccount['uid'], $data['nick']);
                    }
                    // 换绑用户或者身份变更，投队列
                    \Doraemon\cache\EsUpdateCollector::multiInsertBrandIdsForWikiBasic([$data['brand_id']]);
                    break;
                case 2://保存认证信息
                    $authId = $params['id'];
                    if (empty($authId)) {
                        throw new \Exception('不存在的认证信息');
                    }
                    $data = [
                        "nick" => $params['nick'],
                        "company" => $params['company'],
                        "credit_code" => $params['credit_code'],
                        "license" => $params['license'],
                        "license_time" => $params['license_time'],
                        "name" => $params['name'],
                        "phone" => $params['phone'],
                        "email" => $params['email'],
                        "weixin" => $params['weixin'],
                        "letter" => $params['letter'],
                        "letter_time" => $params['letter_time'],
                        "auth_start_time" => $params['auth_start_time'],
                        "auth_end_time" => $params['auth_end_time'],
                        "certificate" => $params['certificate'],
                        "application" => $params['application'],
                        "authorization" => $params['authorization'],
                        'admin_id' => $adminId
                    ];
                    $brandAuthInfo = BrandAccountAuth::getOneByWhere(['id' => $authId]);
                    BrandAccountAuth::updateData($data, ['id' => $authId, 'account_id' => $id]);
                    $oldData = [];
                    $newData = [];
                    foreach ($brandAuthInfo as $key => $value) {
                        if ($value != $data[$key]) {
                            $oldData[$key] = $value;
                            $newData[$key] = $value;
                        }
                    }
                    if ($oldData && $newData) {
                        $oldData['auth_id'] = $brandAuthInfo['id'];
                        $newData['auth_id'] = $brandAuthInfo['id'];
                    }
                    BrandAccountLog::insertData([
                        'account_id' => $id,
                        'operate_uid' => $adminId,
                        'old_data' => json_encode($oldData, JSON_UNESCAPED_UNICODE),
                        'new_data' => json_encode($newData, JSON_UNESCAPED_UNICODE),
                        'operation' => BrandAccountLog::OPERATE_EDIT_ACCOUNT_AUTH,
                    ]);
                    break;
                case 3://保存店铺信息
                    $authId = $request->input('auth_id', 0);
                    $authInfo = $authId ? BrandAccountAuth::getOneByWhere(['id' => $authId]) : [];
                    $data = [
                        "account_id" => $id,
                        "type" => $params['type'],
                        "name" => $params['name'],
                        "url" => trim($params['url']),
                        "shop_id" => $params['shop_id'],
                        "letter" => $params['letter'],
                        "authorization" => $params['authorization'],
                        "shop_status" => BrandAccountShop::SHOP_STATUS_VALID,
                        'admin_id' => $adminId
                    ];
                    if (empty($authId) || ($authInfo && $authInfo['auth_status'] == BrandAccountAuth::AUTH_STATUS_USED)) {
                        $accountShopId = $params['id'] ?? 0;
                        $accountShopInfo = $accountShopId ? BrandAccountShop::getOneByWhere(['id' => $accountShopId]) : [];
                        $newData = $data;
                        $oldData = $accountShopInfo;
                        if ($accountShopId) {
                            BrandAccountShop::updateData($data, ['id' => $accountShopId]);
                            $newData['id'] = $accountShopId;
                        } else {
                            BrandAccountShop::insertData($data);
                        }
                        BrandAccountLog::insertData([
                            'account_id' => $id,
                            'operate_uid' => $adminId,
                            'old_data' => $oldData ? json_encode($oldData, JSON_UNESCAPED_UNICODE) : '',
                            'new_data' => json_encode($newData, JSON_UNESCAPED_UNICODE),
                            'operation' => BrandAccountLog::OPERATE_EDIT_ACCOUNT_SHOP,
                        ]);
                        if ($brandAccount['uid'] && isset($data['shop_id']) && !empty($data['shop_id'])) {
                            if ($data['type'] && $data['type'] < 4) {
                                mWiki::updateData(
                                    ['shop_uid' => $brandAccount['uid']],
                                    ['channel_type' => $data['type'], 'channel_shop_id' => $data['shop_id']]
                                );
                            }
                        }
                    } else {
                        $authShopData[] = $data;
                        $authShop = ($authInfo && $authInfo['shop']) ? json_decode($authInfo['shop'], true) : [];
                        if ($authShop) {
                            $authShopData = array_merge($authShopData, $authShop);
                        }
                        $authShopData = json_encode($authShopData, JSON_UNESCAPED_UNICODE);
                        BrandAccountAuth::updateData(['shop' => $authShopData, 'admin_id' => $adminId], ['id' => $authId]);
                    }
                    break;
            }
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect($requestUrl)->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function delShop(Request $request, $id)
    {
        $data['admin_id'] = Admin::user()->id;
        $info = BrandAccountShop::getOneByWhere(['id' => $id]);
        $url = url('/admin/brand/account/index');
        $adminId = Admin::user()->id;
        if ($info) {
            $data = [
                'shop_status' => BrandAccountShop::SHOP_STATUS_NOVALID,
                'admin_id' => $adminId
            ];
            BrandAccountShop::updateData($data, ['id' => $id]);
            $brandAccount = BrandAccountInfo::getOneByWhere(['id' => $info['account_id']]);
            BrandAccountLog::insertData([
                'account_id' => $info['account_id'],
                'operate_uid' => $adminId,
                'old_data' => json_encode(['id' => $id, 'shop_status' => $info['shop_status']], JSON_UNESCAPED_UNICODE),
                'new_data' => json_encode(['id' => $id, 'shop_status' => $data['shop_status']], JSON_UNESCAPED_UNICODE),
                'operation' => BrandAccountLog::OPERATE_EDIT_ACCOUNT_SHOP,
            ]);
            if ($brandAccount['uid'] && isset($info['shop_id']) && !empty($info['shop_id'])) {
                if ($info['type'] && $info['type'] < 4) {
                    mWiki::updateData(
                        ['shop_uid' => 0],
                        ['channel_type' => $info['type'], 'channel_shop_id' => $info['shop_id']]
                    );
                }
            }
            $url = url('/admin/brand/account/index/' . $info['account_id'] . '/3');
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return redirect($url)->with(compact('success'));
    }

    public function delAccount(Request $request, $id)
    {
        $accountInfo = BrandAccountInfo::getOneByWhere(['id' => $id]);
        if ($accountInfo) {
            if (in_array($accountInfo['account_status'], [BrandAccountInfo::ACCOUNT_STATUS_DEFAULT, BrandAccountInfo::ACCOUNT_STATUS_EXPIRE])) {
                $adminId = Admin::user()->id;
                BrandAccountInfo::updateData(['account_status' => BrandAccountInfo::ACCOUNT_STATUS_DEL, 'admin_id' => $adminId], ['id' => $id]);
                BrandAccountLog::insertData([
                    'account_id' => $id,
                    'operate_uid' => $adminId,
                    'old_data' => json_encode(['id' => $id, 'account_status' => $accountInfo['account_status']], JSON_UNESCAPED_UNICODE),
                    'new_data' => json_encode(['id' => $id, 'account_status' => BrandAccountInfo::ACCOUNT_STATUS_DEL], JSON_UNESCAPED_UNICODE),
                    'operation' => BrandAccountLog::OPERATE_DEL_ACCOUNT,
                ]);
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败，当前状态不允许删除",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "不存在的数据",
            ]);
        }
    }

    public function setBrandType(Request $request, $id, $brandType)
    {
        $adminId = Admin::user()->id;
        $brandAccount = BrandAccountInfo::getOneByWhere(['id' => $id]);
        if ($id && $brandType && isset(mBrand::BRAND_TYPE[$brandType]) && $brandAccount) {
            // 更新品牌账户信息
            $where = [
                'id' => $id,
            ];
            BrandAccountInfo::updateData([
                'brand_type' => $brandType,
                'admin_id' => $adminId,
            ], $where);
            BrandAccountLog::insertData([
                'account_id' => $id,
                'operate_uid' => $adminId,
                'old_data' => json_encode(['id' => $id, 'brand_type' => $brandAccount['brand_type']], JSON_UNESCAPED_UNICODE),
                'new_data' => json_encode(['id' => $id, 'brand_type' => $brandType], JSON_UNESCAPED_UNICODE),
                'operation' => BrandAccountLog::OPERATE_EDIT_ACCOUNT,
            ]);
            // 更新品牌身份
            $result = mBrand::updateBrandInfoById($brandAccount['brand_id'], [
                'brand_type' => $brandType
            ]);
            if (!empty($result)) {
                \Doraemon\cache\EsUpdateCollector::multiInsertBrandIdsForWikiBasic([$brandAccount['brand_id']]);
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
        } else {
            $success = new MessageBag([
                'title' => '操作失败'
            ]);
        }
        return redirect('/admin/brand/account/index')->with(compact('success'));
    }

    public function audit(Request $request, $id, $authStatus)
    {
        $params = $request->all();
        $adminId = Admin::user()->id;
        $authInfo = BrandAccountAuth::getOneByWhere(['id' => $id]);
        if (empty($authInfo)) {
            admin_toastr('不存在的认证信息', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-top-right']);
            return back()->withInput();
        }
        if (!in_array($authStatus, [BrandAccountAuth::AUTH_STATUS_PASS, BrandAccountAuth::AUTH_STATUS_NOPASS])) {
            admin_toastr('非法操作', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-top-right']);
            return back()->withInput();
        }
        $accountId = $authInfo['account_id'];
        $accountInfo = BrandAccountInfo::getOneByWhere(['id' => $accountId]);
        switch ($authStatus) {
            case BrandAccountAuth::AUTH_STATUS_PASS:
                if (!in_array($authInfo['auth_status'], [BrandAccountAuth::AUTH_STATUS_DEFAULT, BrandAccountAuth::AUTH_STATUS_NOPASS])) {
                    admin_toastr('当前状态不允许审核通过', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-top-right']);
                    return back()->withInput();
                }
                if (empty($accountInfo)) {
                    admin_toastr('不存在的账户信息', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-top-right']);
                    return back()->withInput();
                }
                if ($accountInfo['type'] == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                    if (empty($accountInfo['uid']) || empty($accountInfo['brand_id'])) {
                        admin_toastr('账户信息未绑定品牌', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-top-right']);
                        return back()->withInput();
                    }
                }
                if (strtotime($authInfo['letter_time']) <= 0) {
                    admin_toastr('请填写认证申请函有效期', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-top-right']);
                    return back()->withInput();
                }
                if (strtotime($authInfo['auth_start_time']) <= 0 || strtotime($authInfo['auth_end_time']) <= 0) {
                    admin_toastr('请填写认证时间', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-top-right']);
                    return back()->withInput();
                }
                BrandAccountAuth::updateData(['auth_status' => BrandAccountAuth::AUTH_STATUS_PASS, 'reason' => '', 'admin_id' => $adminId], ['id' => $id]);
                BrandAccountLog::insertData([
                    'account_id' => $id,
                    'operate_uid' => $adminId,
                    'old_data' => json_encode(['id' => $id, 'auth_status' => $authInfo['auth_status'], 'reason' => $authInfo['reason']], JSON_UNESCAPED_UNICODE),
                    'new_data' => json_encode(['id' => $id, 'auth_status' => BrandAccountAuth::AUTH_STATUS_PASS, 'reason' => ''], JSON_UNESCAPED_UNICODE),
                    'operation' => BrandAccountLog::OPERATE_AUDIT_ACCOUNT_AUTH,
                ]);
                if ($authStatus == BrandAccountInfo::AUTH_STATUS_PASS) {
                    //审核通过认证信息，如果账户是未启用的，账户的认证状态及店铺等信息同步更改
                    if ($accountInfo && $accountInfo['account_status'] != BrandAccountInfo::ACCOUNT_STATUS_USED) {
                        BrandAccountInfo::updateData(['auth_status' => BrandAccountInfo::AUTH_STATUS_PASS, 'nick' => $authInfo['nick']], ['id' => $accountId]);
                        $shopList = json_decode($authInfo['shop'], true);
                        if (is_array($shopList)) {
                            $addIds = [];
                            foreach ($shopList as $row) {
                                if ($row['shop_id']) {
                                    $data = [
                                        'account_id' => $accountId,
                                        'type' => $row['type'],
                                        'other_type' => $row['other_type'] ?? 0,
                                        'name' => $row['name'],
                                        'url' => $row['url'],
                                        'shop_id' => $row['shop_id'],
                                        'letter' => $row['letter'],
                                        'authorization' => $row['authorization'],
                                        'shop_status' => BrandAccountShop::SHOP_STATUS_VALID,
                                        'admin_id' => $adminId
                                    ];
                                    $shopInfo = BrandAccountShop::getOneByWhere(['account_id' => $accountId, 'shop_id' => $row['shop_id'], 'type' => $row['type']]);
                                    if ($shopInfo) {
                                        BrandAccountShop::updateData($data, ['id' => $shopInfo['id']]);
                                        $addIds[] = $shopInfo['id'];
                                    } else {
                                        $accountShopId = BrandAccountShop::insertData($data);
                                        if ($accountShopId) {
                                            $addIds[] = $accountShopId;
                                        }
                                    }
                                }
                            }
                            if ($addIds && $accountId) {
                                BrandAccountShop::updateData(['shop_status' => BrandAccountShop::SHOP_STATUS_NOVALID], ['id[!]' => $addIds, 'account_id' => $accountId]);
                            }
                        }
                    }
                }
                //审核通过后默认关注品牌小秘书
                Follow::FollowMultiUsers($accountInfo['uid'], self::DEFAULT_BRAND_UID, 'autoFollow');
                \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                    'msgCode' => BrandAccountInfo::SEND_CODE_PASS,
                    'to_uid' => $accountInfo['uid'],
                ], \Doraemon\cache\Queue::QUEUE_DORAEMON);

                $title = '品牌认证通知';
                $brandId = $accountInfo['brand_id'];
                $brandInfo = Brand::getInfo($brandId);
                $brandName = $brandInfo['brand_name'];
                $uid = $accountInfo['uid'];
                $phone = $authInfo ? $authInfo['phone'] : '';
                $msg = <<<MSG
## {$title}
- 品牌id: **{$brandId}**
- 品牌名称: **{$brandName}**
- 关联账户uid: **{$uid}** 
- 手机号: **{$phone}**
- 用户提交的身份认证已审核成功
### 请销售同学尽快沟通付款事宜
MSG;
                DingTalkAlert::sendMarkdownMsg(DingTalkAlert::BRAND_AUTH_PASS_KEY, $title, $msg, true);
                $success = new MessageBag([
                    'title' => '操作成功'
                ]);
                return back()->withInput()->with(compact('success'));
                break;
            case BrandAccountAuth::AUTH_STATUS_NOPASS:
                if ($authInfo['auth_status'] != BrandAccountAuth::AUTH_STATUS_DEFAULT) {
                    admin_toastr('当前状态不允许审核不通过', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-top-right']);
                    return back()->withInput();
                }
                $reason = $params['reason'] ?? '';
                if (!$reason) {
                    admin_toastr('请输入审核不通过原因', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-top-right']);
                    return back()->withInput();
                }
                BrandAccountAuth::updateData(['auth_status' => BrandAccountAuth::AUTH_STATUS_NOPASS, 'reason' => $reason, 'admin_id' => $adminId], ['id' => $id]);
                BrandAccountLog::insertData([
                    'account_id' => $id,
                    'operate_uid' => $adminId,
                    'old_data' => json_encode(['id' => $id, 'auth_status' => $authInfo['auth_status'], 'reason' => $authInfo['reason']], JSON_UNESCAPED_UNICODE),
                    'new_data' => json_encode(['id' => $id, 'auth_status' => BrandAccountAuth::AUTH_STATUS_NOPASS, 'reason' => $reason], JSON_UNESCAPED_UNICODE),
                    'operation' => BrandAccountLog::OPERATE_AUDIT_ACCOUNT_AUTH,
                ]);
                //审核不通过认证信息，如果账户是未启用的，账户的认证状态同步更改
                if ($accountInfo && $accountInfo['account_status'] != BrandAccountInfo::ACCOUNT_STATUS_USED) {
                    BrandAccountInfo::updateData(['auth_status' => BrandAccountInfo::AUTH_STATUS_NOPASS], ['id' => $accountId]);
                }
                if ($accountInfo['uid']) {
                    \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', [
                        'msgCode' => BrandAccountInfo::SEND_CODE_NOPASS,
                        'to_uid' => $accountInfo['uid'],
                    ], \Doraemon\cache\Queue::QUEUE_DORAEMON);
                }
                $success = new MessageBag([
                    'title' => '操作成功'
                ]);
                return redirect(url('/admin/brand/account/auth/noPass/{id}' . $id . '?code=1'))->with(compact('success'));
                break;
        }
    }

    public function noPass(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
SCRIPT;
            Admin::script($script);
        }
        $form = new Form(['id' => $id]);
        $form->hidden('id', 'id');
        $form->textarea('reason', '不通过原因')->required();
        $form->action('/admin/brand/account/auth/' . $id . '/audit/' . BrandAccountAuth::AUTH_STATUS_NOPASS);
        $content->row($form);
        return $content->header('不通过原因');
    }

    public function authList(Request $request, Content $content)
    {
        if (!$request->input('auth_status')) {
            $request->merge(['auth_status' => [0 => BrandAccountAuth::AUTH_STATUS_DEFAULT]]);
        }
        $type = $request->input('type', BrandAccountInfo::ACCOUNT_TYPE_BRAND);
        $params = $request->all();
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : 10;
        //搜索过滤
        if (isset($params['uid']) && $params['uid']) {
            $accountId = BrandAccountInfo::getAllByWhere([
                'uid' => $params['uid'],
                'type' => $type,
                'account_status[!]' => BrandAccountInfo::ACCOUNT_STATUS_DEL,
                'ORDER' => ['id' => 'DESC']
            ], 'id'
            );
            $where['account_id'] = $accountId;
        }
        if (isset($params['nick']) && strlen($params['nick']) > 0) {
            $where['nick'] = trim($params['nick']);
        }
        if (isset($params['brand_id']) && $params['brand_id']) {
            $accountIds = BrandAccountInfo::getAllByWhere(['brand_id' => $params['brand_id']], 'id');
            if ($accountIds) {
                $where['account_id'] = $accountIds;
            }
        }
        if (isset($params['brand_name']) && $params['brand_name']) {
            $brandIds = mBrand::selectByWhere(['brand_name[~]' => $params['brand_name'], 'status' => mBrand::STATUS_NORMAL], ['id']);
            $brandIds = $brandIds ? array_column($brandIds, 'id') : [];
            if ($brandIds) {
                $accountIds = BrandAccountInfo::getAllByWhere(['brand_id' => $brandIds], 'id');
                if ($accountIds) {
                    $where['account_id'] = $accountIds;
                }
            }
        }
        if (isset($params['auth_status'])) {
            $where['auth_status'] = $params['auth_status'];
        }
        $where['type'] = $type;
        $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
        $where['ORDER'] = ['id' => 'DESC'];
        $result = BrandAccount::admGetAuthList($where);

        $list = !empty($result['list']) ? $result['list'] : [];
        $total = $result['total'];
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $params['per_page'],
        ]);
        $allPackageTypes = BrandPackage::allPackageTypes();
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($allPackageTypes, $type) {
            $grid->filter(function (Grid\Filter $filter) use ($allPackageTypes, $type) {
                $filter->disableIdFilter();
                if ($type == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                    $filter->column(1 / 2, function ($filter) {
                        $filter->dropDown('uid_value', [
                            'uid' => 'uid',
                            'nick' => '用户昵称',
                        ]);
                        $filter->dropDown('brand_value', [
                            'brand_id' => '品牌id',
                            'brand_name' => '品牌名称',
                        ]);
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) use ($allPackageTypes) {
                        $filter->equal('auth_status', '认证状态')->multipleSelect(BrandAccountInfo::AUTH_STATUS_MAP);
                    });
                } else {
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('uid', 'uid');
                        $filter->equal('nick', '用户昵称');
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) use ($allPackageTypes) {
                        $filter->equal('auth_status', '认证状态')->multipleSelect(BrandAccountInfo::AUTH_STATUS_MAP);
                    });
                }
                $filter->expand();
            });

            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->column('id', '认证ID')->width(80);
            $grid->column('account_id', '账户ID')->width(80);
            $grid->column('uid', 'uid')->width(80);
            $grid->column('nick', '昵称')->width(100);
            $grid->column('avatar_small', '图像')->display(function () {
                return '<img src="' . $this->small_avatar . '">';
            })->width(80);
            if ($type == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
                $grid->column('brand_id', '品牌id')->width(80);
                $grid->column('brand_name', '品牌名称')->width(120);
                $grid->column('logo', '品牌logo')->display(function () {
                    return '<img src="' . $this->logo . '" style="width:52px;height:52px">';
                })->width(80);
                $grid->column('pack_type', '品牌套餐')->display(function () use ($allPackageTypes) {
                    return $allPackageTypes[$this->pack_type];
                })->width(120);
                $grid->column('brand_type', '品牌身份')->display(function () {
                    return mBrand::BRAND_TYPE[$this->brand_type];
                })->width(120);
            }
            $grid->column('account_status', '账户状态')->display(function () {
                return BrandAccountInfo::ACCOUNT_STATUS_MAP[$this->account_status];
            })->width(120);
            $grid->column('auth_status', '认证状态')->display(function () {
                return BrandAccountInfo::AUTH_STATUS_MAP[$this->auth_status];
            })->width(120);
            $grid->column('add_time', '申请时间')->width(120);
            $grid->column('in_end_time', '入驻结束')->width(120);
            $grid->column('tags', '标记类型')->width(80);
            $grid->column('reason', '说明')->width(80)->limit(30);
            $grid->column('admin_id', '处理人')->display(function () {
                if (!$this->admin_id) {
                    return '-';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            })->width(80);

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->disableEdit();
                $actions->disableDelete();
                if (in_array($actions->row->auth_status, [BrandAccountAuth::AUTH_STATUS_DEFAULT, BrandAccountAuth::AUTH_STATUS_NOPASS])) {
                    $actions->append("<a href=\"/admin/brand/account/index/" . $actions->row->account_id . "/1?auth_id=" . $actions->row->id . "\"
                    class=\"btn btn-primary\" style=\"margin-top: 5px;margin-left: 5px;\">审核</a>");
                } else {
                    $actions->append("<a href=\"/admin/brand/account/index/" . $actions->row->account_id . "/2?auth_id=" . $actions->row->id . "\"
                    class=\"btn btn-primary\" style=\"margin-top: 5px;margin-left: 5px;\">编辑</a>");
                }
                if ($actions->row->auth_status != BrandAccountInfo::AUTH_STATUS_USED && $actions->row->account_status != BrandAccountInfo::ACCOUNT_STATUS_USED) {
                    $actions->disableDelete(false);
                }
            });
        });

        if ($type == BrandAccountInfo::ACCOUNT_TYPE_BRAND) {
            $header = '品牌认证管理';
            $url = '/account/auth/index';
        } else {
            $header = '店铺认证管理';
            $url = '/account/auth/index?type=' . BrandAccountInfo::ACCOUNT_TYPE_SHOP;
        }
        return $content
            ->header($header)
            ->breadcrumb(
                ['text' => $header, 'url' => $url]
            )
            ->body($listGrid);
    }

    public function delAuth(Request $request, $id)
    {
        $authInfo = BrandAccountAuth::getOneByWhere(['id' => $id]);
        if ($authInfo) {
            $accountInfo = BrandAccountInfo::getOneByWhere(['id' => $authInfo['account_id']]);
            if ($authInfo['auth_status'] != BrandAccountAuth::AUTH_STATUS_USED && $accountInfo['account_status'] != BrandAccountInfo::ACCOUNT_STATUS_USED) {
                $adminId = Admin::user()->id;
                BrandAccountAuth::updateData(['auth_status' => BrandAccountAuth::AUTH_STATUS_DEL, 'admin_id' => $adminId], ['id' => $id]);
                BrandAccountLog::insertData([
                    'account_id' => $id,
                    'operate_uid' => $adminId,
                    'old_data' => json_encode(['id' => $id, 'auth_status' => $authInfo['auth_status']], JSON_UNESCAPED_UNICODE),
                    'new_data' => json_encode(['id' => $id, 'auth_status' => BrandAccountAuth::AUTH_STATUS_DEL], JSON_UNESCAPED_UNICODE),
                    'operation' => BrandAccountLog::OPERATE_DEL_AUTH,
                ]);
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败，当前状态不允许删除",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "不存在的数据",
            ]);
        }
    }

    public function openShop(Request $request, $id)
    {
        $adminId = Admin::user()->id;
        $brandAccount = BrandAccountInfo::getOneByWhere(['id' => $id]);
        if ($id && $brandAccount && $brandAccount['type'] == BrandAccountInfo::ACCOUNT_TYPE_SHOP) {
            if (!in_array($brandAccount['account_status'], [BrandAccountInfo::ACCOUNT_STATUS_DEFAULT, BrandAccountInfo::ACCOUNT_STATUS_EXPIRE])) {
                admin_toastr('当前账户的状态不支持开通', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-bottom-right']);
                return back()->withInput();
            }
            if (!$brandAccount['uid']) {
                admin_toastr('当前账户的为绑定uid', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-bottom-right']);
                return back()->withInput();
            }
            $today = date('Y-m-d');
            if ($today >= $brandAccount['in_start_time'] && $today <= $brandAccount['in_end_time']) {
            } else {
                admin_toastr('当前账户入驻时间不在有效期内，请去编辑账户的入驻时间', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-bottom-right']);
                return back()->withInput();
            }
            $authInfo = BrandAccountAuth::getOneByWhere(['account_id' => $id, 'auth_status' => BrandAccountAuth::AUTH_STATUS_PASS]);
            if (!$authInfo) {
                admin_toastr('认证信息还未审核，请先审核认证信息', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-bottom-right']);
                return back()->withInput();
            }
            $nick = $brandAccount['nick'];
            // 更新店铺账户信息
            $accountData = [
                'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
                'auth_status' => BrandAccountInfo::AUTH_STATUS_USED,
                'admin_id' => $adminId
            ];

            if ($authInfo) {
                $nick = $authInfo['nick'];
                $accountData['nick'] = $authInfo['nick'];
            }
            BrandAccountInfo::updateData($accountData, ['id' => $brandAccount['id']]);
            BrandAccountAuth::updateData([
                'auth_status' => BrandAccountAuth::AUTH_STATUS_USED,
                'admin_id' => $adminId,
            ], [
                'account_id' => $id,
                'auth_status' => BrandAccountAuth::AUTH_STATUS_PASS
            ]);
            BrandAccountLog::insertData([
                'account_id' => $id,
                'operate_uid' => $adminId,
                'old_data' => json_encode(['account_status' => $brandAccount['account_status'], 'auth_status' => $brandAccount['auth_status'], 'nick' => $brandAccount['nick']], JSON_UNESCAPED_UNICODE),
                'new_data' => json_encode($accountData, JSON_UNESCAPED_UNICODE),
                'operation' => BrandAccountLog::OPERATE_OPEN_SHOP_ACCOUNT,
            ]);

            $shopList = $authInfo ? json_decode($authInfo['shop'], true) : [];
            if (is_array($shopList)) {
                $addIds = [];
                foreach ($shopList as $row) {
                    if ($row['shop_id']) {
                        $data = [
                            'account_id' => $brandAccount['id'],
                            'type' => $row['type'],
                            'other_type' => $row['other_type'] ?? 0,
                            'name' => $row['name'],
                            'url' => $row['url'],
                            'shop_id' => $row['shop_id'],
                            'letter' => $row['letter'],
                            'authorization' => $row['authorization'],
                            'shop_status' => BrandAccountShop::SHOP_STATUS_VALID,
                            'admin_id' => 0
                        ];
                        $shopInfo = BrandAccountShop::getOneByWhere(['account_id' => $brandAccount['id'], 'shop_id' => $row['shop_id'], 'type' => $row['type']]);
                        if ($shopInfo) {
                            BrandAccountShop::updateData($data, ['id' => $shopInfo['id']]);
                            $addIds[] = $shopInfo['id'];
                        } else {
                            $accountShopId = BrandAccountShop::insertData($data);
                            if ($accountShopId) {
                                $addIds[] = $accountShopId;
                            }
                        }
                    }
                }
                if ($addIds && $brandAccount['id']) {
                    BrandAccountShop::updateData(['shop_status' => BrandAccountShop::SHOP_STATUS_NOVALID], ['id[!]' => $addIds, 'account_id' => $brandAccount['id']]);
                }
            }
            $memberData = [
                'type' => mMember::AUTH_USER_BRAND,
                'status' => mMember::STATUS_NORMAL,
            ];
            $result = Member::nick(false, true, $nick, $brandAccount['uid'], mMember::AUTH_USER_BRAND);
            if ($result === true || $result === '30天之内只能修改一次用户名' || $result === '该昵称已被占用') {
                $memberData['nick'] = $nick;
            }
            //更新主账户类别，普通用户改变类别，品牌用户不用改变类别
            mMember::updateUserInfo($brandAccount['uid'], $memberData);
            cUser::deleteUserInfo($brandAccount['uid']);
            // 标记用户强制退出
            cUserAuthStatus::setAuthType($brandAccount['uid'], mMember::AUTH_USER_BRAND);

            $success = new MessageBag([
                'title' => '开通成功'
            ]);
        } else {
            $success = new MessageBag([
                'title' => '开通失败'
            ]);
        }
        return redirect('/admin/brand/account/index?type=2')->with(compact('success'));
    }

    private function getCurrentUrl()
    {
        $requestUlr = url($_SERVER['REQUEST_URI']);
        $urlArr = parse_url($requestUlr);
        $query = '';
        if (isset($urlArr['query'])) {
            $query = $urlArr['query'];
            parse_str($query, $queryArr);
            if (isset($queryArr['_pjax'])) {
                unset($queryArr['_pjax']);
            }
            $query = http_build_query($queryArr);
            $query = $query ? ('?' . $query) : '';
        }
        $url = $urlArr['scheme'] . '://' . $urlArr['host'] . $urlArr['path'] . $query;
        return $url;
    }
}
